class CanvasComponent {
  constructor(mainContext, callback) {
    this.mainContext = mainContext;
    this.callback = callback;

    this.cacheCanvas = wx.createCanvas();
    this.cacheCtx = this.cacheCanvas.getContext('2d');
  }
}
 
class CountDownText extends CanvasComponent {
  constructor(mainContext, customStyles, callback) {
    super(mainContext, callback);

    this.isStartTicking = false;

    this.cacheCanvas.width = 300;
    this.cacheCanvas.height = 300;
    this.cacheCtxStyles = customStyles;
  }

  __makeTextByTickTime = () => {
    const currentDateTimeSeconds = new Date().getTime() / 1000;
    const secondsDiff = Math.floor(currentDateTimeSeconds - this.tickStartTimeSecond);
    let displayText = null;

    switch (secondsDiff) {
      case 0:
        displayText = '';
        break;
      case 1:
        displayText = '3';
        break;
      case 2:
        displayText = '2';
        break;
      case 3:
        displayText = '1';
        break;
      default:
        break;
    }

    return displayText;
  }

  __setCacheCtxStyles(fillText) {
    this.cacheCtx.fillStyle = this.cacheCtxStyles.fillStyle;
    this.cacheCtx.font = this.cacheCtxStyles.font;
    this.cacheCtx.fillText(
      fillText,
      this.cacheCtxStyles.textPosition.x,
      this.cacheCtxStyles.textPosition.y
    );
  }

  drawToMainCanvas = () => {
    if (this.isStartTicking === false) {
      this.tickStartTimeSecond = new Date().getTime() / 1000;
      this.isStartTicking = true;
    }

    const displayText = this.__makeTextByTickTime();
    if (displayText === null) {
      this.isStartTicking = false;

      this.callback();
    } else {
      this.cacheCtx.clearRect(0, 0, this.cacheCanvas.width, this.cacheCanvas.height);
      this.__setCacheCtxStyles(displayText);
      this.mainContext.drawImage(this.cacheCanvas, 0, 0);
    }
  }
}

class BackButton extends CanvasComponent {
  constructor(mainContext, customStyles, callback) {
    super(mainContext, callback);
    this.cacheCanvas.width = 300;
    this.cacheCanvas.height = 300;

    this.cacheCtx.fillStyle = 'yellow';
    this.cacheCtx.fillRect(0, 0, 100, 100);
  }

  drawToMainCanvas = () => {
    this.mainContext.drawImage(this.cacheCanvas, 0, 0);
  }
}

export { BackButton, CountDownText }